require(["core", "jQuery", "coAjax", "queryString", "hash_routie", "moment"], function(jSouper, $, coAjax, QueryString, hash_routie, moment) {
	function _get_statistical_data(options) {
		coAjax.get(appConfig.bus.statistical_ach_by_date, {
			from: options.from,
			to: options.to,
			filter_by_pay_method: options.filter_by_pay_method,
			filter_pay_method_list: options.filter_pay_method_list
		}, function(result) {
			App.set("$Cahce.bus.statistical.info", result.result);
			console.log(result.result.filter_pay_method_list);
			_refresh_chart_frame();
		});
	};
	var PAY_METHOD_array = jSouper.$.order.toArray(appConfig.PAY_METHOD);
	App.set("$Cache.PAY_METHOD_array", PAY_METHOD_array);
	var _qs;
	hash_routie.on("statistical", function() {
		_qs = new QueryString(location.hash);
		var _from = +_qs.get("from");
		var _to = +_qs.get("to");
		if (_from > _to) {
			//不符合规范的数据
			_from = 0;
			_to = 0;
		}
		var now = _to ? new Date(_to) : new Date;
		if (_from) {
			var month_ago = new Date(_from);
		} else {
			month_ago = new Date;
			month_ago.setDate(month_ago.getDate() - 30);
			month_ago = new Date(month_ago.toDateString());
		}

		var filter_pay_method_list = _qs.get("filter_pay_method_list");
		filter_pay_method_list = filter_pay_method_list ? filter_pay_method_list.split(",") : null;
		_get_statistical_data({
			from: +month_ago,
			to: +now,
			filter_by_pay_method: !!jSouper.$.strToBool(_qs.get("filter_by_pay_method")),
			filter_pay_method_list: filter_pay_method_list
		});
	});
	//重新拉取数据
	App.set("$Event.bus.statistical.get_statistical_data", function() {
		console.log("reload")
		var options = App.get("$Cahce.bus.statistical.info")
		console.log(options.filter_pay_method_list)
		hash_routie.hash({
			from: options.from,
			to: options.to,
			filter_by_pay_method: options.filter_by_pay_method,
			filter_pay_method_list: options.filter_pay_method_list
		});
	});

	function _echarts_run_code() {

		var _max_ach_num = 0; //最大的订单数量，为了实现点的显示在100px以内，所以需要最大数量来做等比缩放;
		require(
			[
				'echarts',
				'echarts/chart/line' // 使用柱状图就加载bar模块，按需加载
			],
			function(ec) {
				// 基于准备好的dom，初始化echarts图表
				var myChart = ec.init(document.getElementById('main'));
				var option = {
					title: {
						text: '__echarts_title__',
						subtext: '__echarts_subtext__'
					},
					tooltip: {
						trigger: 'item',
						formatter: function(params) {
							var date = new Date(params.value[0]);
							data = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate();
							return data + '<br/>' + params.value[1].toFixed(2) + " 元, " + params.value[2] + " 件";
						}
					},
					toolbox: {
						show: true,
						feature: {
							mark: {
								show: true
							},
							dataView: {
								show: true,
								readOnly: false
							},
							restore: {
								show: true
							},
							saveAsImage: {
								show: true
							}
						}
					},
					dataZoom: {
						show: true,
						start: 0
					},
					legend: {
						data: ['订单金额与数量']
					},
					grid: {
						y2: 80
					},
					xAxis: [{
						type: 'time',
						splitNumber: 15
					}],
					yAxis: [{
						type: 'value',
						min: 0
					}],
					series: [{
						name: '订单金额与数量',
						type: 'line',
						showAllSymbol: true,
						symbolSize: function(value) {
							return 10 * value[2] / _max_ach_num + 2;
						},
						// data: (function() {
						// 	var d = [];
						// 	var len = 0;
						// 	var now = new Date();
						// 	var value;
						// 	while (len++ < 200) {
						// 		d.push([
						// 			new Date(2014, 9, 1, 0, len * 10000), (Math.random() * 90).toFixed(2) - 0, (Math.random() * 100).toFixed(2) - 0
						// 		]);
						// 	}
						// 	return d;
						// })()
						data: function() {
							return __json_data__.map(function(item) {
								_max_ach_num = Math.max(_max_ach_num, item.ach_num);
								return [new Date(item.time), item.total_cash, item.ach_num]
							});
						}()
					}]
				};
				// 为echarts对象加载数据 
				myChart.setOption(option);
			}
		);

	}
	//改变显示方式
	function _refresh_chart_frame() {
		var frame = document.getElementById("statistical-chart-frame");
		if (!frame) {
			return
		}
		frame = frame.contentWindow;

		var options = App.get("$Cahce.bus.statistical.info");
		var code = _echarts_run_code.toString()
		code = code.substring(code.indexOf("{") + 1, code.length - 1);
		code = code.replace("__echarts_title__", moment(+options.from).format("YYYY-MM-DD") + " ~ " + moment(+options.to).format("YYYY-MM-DD") + " 订单统计折线图");
		code = code.replace("__echarts_subtext__", "[支付方式]: 所有");
		code = code.replace("__json_data__", JSON.stringify(jSouper.map(options.statis_info, function(statis_info) {
			return {
				time: +statis_info.time,
				ach_num: statis_info.achs.length,
				total_cash: statis_info.total_cash
			}
		}).sort(function(a, b) {
			return b.time - a.time
		}) /**/ ));


		var project_name = 'ECharts-Run-Code:' + Math.random().toString(24).substr(2);
		App.set("$Cache.bus.statistical.chart_frame_project_name", project_name);

		var messenger = new Messenger('Parent', project_name);
		messenger.addTarget(frame, "echarts-base-iframe");
		messenger.listen(function(msg) {
			if (msg === "WINDOW-ONLOAD") {
				console.log("chart_frame load, send draw code.");
				messenger.send("RUN_SCRIPT" + code);
			}
		});
	}
	App.set("$Event.bus.statistical.toggle_show_method", function() {
		var _v = !App.get("$State.bus.statistical.show_chart");
		App.set("$State.bus.statistical.show_chart", _v);
		if (_v) {
			_refresh_chart_frame();
		}
	});
});